package com.ldg.seckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.ld.utils.MyDate;
import com.ldg.seckill.entity.SeckillStatus;
import com.ldg.seckill.entity.StatusCode;
import com.ldg.seckill.service.MultiThreadingCreateOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ldg.seckill.entity.TbSeckillOrder;
import com.ldg.seckill.mapper.TbSeckillOrderMapper;
import com.ldg.seckill.service.TbSeckillOrderService;
/**
 * @Author: Liudao
 * @Date: 2022-10-21-16:54
 * @Description:
 */
@Service
public class TbSeckillOrderServiceImpl extends ServiceImpl<TbSeckillOrderMapper, TbSeckillOrder> implements TbSeckillOrderService{

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private MultiThreadingCreateOrder createOrder;
    @Override
    public void saveOrder(String name, String id) {
        //得到最近的秒杀时间
        String dateStr = MyDate.getDateStr(MyDate.getDateMenus().get(0));
        //构造订单状态对象
        SeckillStatus status = new SeckillStatus(name, new Date(), 1, new Long(id), dateStr);
        //第一件事，避免重复排队
        Long count = redisTemplate.boundHashOps("UserQueueCount").increment(name, 1);
        assert count != null;
        if (count > 1){
            throw new RuntimeException(StatusCode.REPERROR + "");
        }
        //第二件事，保证公平性，从左面将下单用户放入队列
        redisTemplate.boundListOps("SeckillOrderQueue").leftPush(JSON.toJSONString(status));
        //第三件事，将上面用户的状态值备份
        redisTemplate.boundHashOps("UserQueueStatus").put(name,JSON.toJSONString(status));
        //第四件事，开始下单
        createOrder.CreatOrder();
    }
}
